package com.zb.service.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.zb.common.exception.BusinessException;
import com.zb.common.mapper.DownLoadMapper;
import com.zb.common.po.config.ConfigInfo;
import com.zb.common.po.enums.PageSize;
import com.zb.common.po.model.DownLoad;
import com.zb.common.po.query.DownLoadQuery;
import com.zb.common.utils.PaginationResult;
import com.zb.common.utils.SimplePage;
import com.zb.service.DownloadService;

@Service
public class DownloadServiceImpl implements DownloadService {
    Logger logger = LoggerFactory.getLogger(DownloadServiceImpl.class);
    @Resource
    private ConfigInfo configInfo;

    @Resource
    private DownLoadMapper downLoadMapper;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = BusinessException.class)
    public void downloadFile(String userId, HttpServletRequest request,
            HttpServletResponse response, Integer type)
            throws BusinessException {
        if (null == type) {
            type = 0;
        }
        InputStream in = null;
        OutputStream out = null;
        try {
            DownLoad download = this.downLoadMapper
                    .selectDownLoadByUserId(userId);
            if (download.getDownloadCount() == 0) {
                throw new BusinessException("你的下载次数已经用完");
            }
            download.setDownloadCount(download.getDownloadCount() - 1);
            this.downLoadMapper.updateDownLoad(download);

            File file = null;
            // 开始下载
            String fileName = type == 0 ? configInfo.getSourceCodeName4Maven()
                    : configInfo.getSourceCodeName4Normal();
            String realPath = configInfo.getSourceCodeDownloadPath() + fileName;
            file = new File(realPath);
            in = new FileInputStream(file);
            out = response.getOutputStream();
            response.setContentType("application/x-msdownload; charset=UTF-8");
            // 解决中文文件名乱码问题
            if (request.getHeader("User-Agent").toLowerCase()
                    .indexOf("firefox") > 0) {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器
            } else {
                fileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器
            }
            response.setHeader("Content-Disposition", "attachment;filename=\""
                    + fileName + "\"");
            byte[] byteData = new byte[1024 * 500];
            int len = 0;
            while ((len = in.read(byteData)) != -1) {
                out.write(byteData, 0, len); // write
            }
            out.flush();
        } catch (Exception e) {
            logger.error("下载异常：", e);
            throw new BusinessException("下载异常,请联系多多洛");
        } finally {
            if (null != in) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public PaginationResult<DownLoad> findDownLoadList(DownLoadQuery query) {
        int count = this.downLoadMapper.selectDownLoadCount(query);
        int pageSize = PageSize.SIZE20.getSize();
        int pageNo = 0;
        if (null != query.getPageNo()) {
            pageNo = query.getPageNo();
        }
        SimplePage page = new SimplePage(pageNo, count, pageSize);
        query.setPage(page);
        List<DownLoad> list = this.downLoadMapper.selectDownLoadList(query);
        PaginationResult<DownLoad> result = new PaginationResult<DownLoad>(
                page, list);
        return result;
    }

    @Override
    public DownLoad findDownloadByUserId(String userId) {
        return downLoadMapper.selectDownLoadByUserId(userId);
    }

}
